package hardcode2013;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

public class SessionUtil {
	public static String getAuthUsername(HttpServletRequest req) {
		String username = null;
		HttpSession session = req.getSession();
		if (session.getAttribute("auth_username") != null) username = (String) session.getAttribute("auth_username");
		return username;
	}
	public static void setAuthUsername(HttpServletRequest req, String username) {
		req.getSession().setAttribute("auth_username", username);
	}
	public static void removeAuthUsername(HttpServletRequest req) {
		req.getSession().removeAttribute("auth_username");
	}
	
	public static String getMessage(HttpServletRequest req) {
		String message = null;
		HttpSession session = req.getSession();
		if (session.getAttribute("msg") != null) message = (String) session.getAttribute("msg");
		return message;
	}
	public static void setMessage(HttpServletRequest req, String message) {
		req.getSession().setAttribute("msg", message);
	}
	public static void removeMessage(HttpServletRequest req) {
		req.getSession().removeAttribute("msg");
	}
	
	public static String getAuthKey(HttpServletRequest req) {
		String key = null;
		HttpSession session = req.getSession();
		if (session.getAttribute("auth_key") != null) key = (String) session.getAttribute("auth_key");
		return key;
	}
	public static void setAuthKey(HttpServletRequest req, String username) {
		req.getSession().setAttribute("auth_key", Crypto.SHA1Encrypt(username) + Crypto.SHA1Encrypt(String.valueOf(new Date().getTime())));
	}
	
	public static boolean authUser(HttpServletRequest req, String username, String authKey) {
		String sessionAuthKey = getAuthKey(req);
		return (username != null && authKey != null && sessionAuthKey != null && authKey.equals(sessionAuthKey));
	}
}
